﻿#include "PowerOutputThread.h"
#include "GlobalHeader.h"

PowerOutputThread::PowerOutputThread(QObject *parent)
	: QThread(parent)
{

}

PowerOutputThread::~PowerOutputThread()
{
}

void PowerOutputThread::PutFileToDeal(const QString &strFileName, const unsigned short usDelay)
{
	m_strFileName = strFileName;
	m_usDelayTime = usDelay;
}

void PowerOutputThread::run()
{
	if (!g_pPowerOutput)
	{
		gAddLog(LOGTYPE_ERROR, "窗口指针为空");
		return;
	}
	QQueue<QPair<unsigned long long, float>> Queen;
	if (!LoadFile(m_strFileName, Queen))
		return;
	if (Queen.isEmpty())
	{
		gAddLog(LOGTYPE_ERROR, "文件内容为空");
		return;
	}
	unsigned long long ullFreq = 0;
	do 
	{
		QPair<unsigned long long ,float> CurData = Queen.dequeue();
		//发送SCPI指令
		QString strCmd;
		bool bResult = false;
		if (CurData.first != ullFreq)
		{
			ullFreq = CurData.first;
			strCmd = QString().sprintf(":FREQ %lluHz\n", ullFreq);

			g_pPowerOutput->SendCmd(strCmd);
		}
		strCmd = QString().sprintf("POW:AMPL %fdbm\n", CurData.second);

		g_pPowerOutput->SendCmd(strCmd);
		QThread::msleep(m_usDelayTime);
	} while (!Queen.isEmpty());
	//发送TCP
	emit g_pPowerOutput->signal_CloseNet();
}

bool PowerOutputThread::LoadFile(const QString strFileName, QQueue <QPair<unsigned long long, float>> &Queen)
{
	QFile CurFile(strFileName);
	if (!CurFile.open(QFile::ReadOnly))
	{
		gAddLog(LOGTYPE_ERROR, CurFile.errorString());
		return false;
	}
	qint64 PerDt = QDateTime::currentMSecsSinceEpoch();
	gAddLog(LOGTYPE_MESSAGE, u8"系统正在处理:" + strFileName);
	//	QByteArray ByteArrayLineData;
	//第一行表头扔掉
	QTextStream CurTextStream(&CurFile);
	CurTextStream.readLine();
	do 
	{
		QString strData = CurTextStream.readLine();
		QStringList DataList = strData.split(',');
		if (DataList.size() >= 2)
		{
			QPair<unsigned long long, float> Pair;
			Pair.first = DataList.at(0).toULongLong();
			Pair.second = DataList.at(1).toFloat();
			Queen.enqueue(Pair);
		}
		else
		{
			gAddLog(LOGTYPE_ERROR, u8"字符串检测异常:" + strData);
		}
	}	 
	while (!g_bExit && !isInterruptionRequested() && !CurTextStream.atEnd());
	CurFile.close();
	QString strLog = u8"文件处理完成:" + strFileName;
	strLog += u8"  用时:" + QString::number(QDateTime::currentMSecsSinceEpoch() - PerDt);
	strLog += "ms";
	gAddLog(LOGTYPE_MESSAGE, strLog);
	return true;
}
